import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { Message } from './message.entity'
import { MessageDto } from './message.dto'
import { IMessage } from './type'
import { UserService } from '../user/user.service'

@Injectable()
export class MessageService {
    constructor(
        @InjectRepository(Message)
        private readonly messageRespository: Repository<Message>,
        private readonly userService: UserService
    ){}

    // 保存消息
    async saveMessage(messageDto:MessageDto){
        try {
            const message = new Message()
            message.content = messageDto.content
            message.sendTime = messageDto.send_time + ''
            message.sendUser = messageDto.sendUser
            const res = await this.messageRespository.save(message)
            return Promise.resolve(res)
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 处理消息保存
    async handleMessageSave(message:IMessage){
        const { send_user_id,send_time,content } = message        
        try {
            const user = await this.userService.findUserById(send_user_id)
            console.log(user);
            
            const messageDto:MessageDto = {
                send_time,
                content,
                sendUser: user
            }
            await this.saveMessage(messageDto)
        } catch (error) {
            console.log(error);
        }
    }

    // 获取历史消息
    async getHistoryMsg():Promise<Message[]>{
        try {
            const historyMessage = await this.messageRespository.find({ relations:['sendUser'] })
            return historyMessage
        } catch (error) {
            throw error
        }
    }
}